/*
 * Copyright 2010 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

public class ServiceManager implements Service {

	private Map<Class<? extends Service>, Service> services;

	public static ServiceManager getInstance() {
		return ServiceManagerHolder.serviceManager;
	}

	private static class ServiceManagerHolder {
		private static final ServiceManager serviceManager = new ServiceManager();
	}

	private ServiceManager() {
		services = new HashMap<Class<? extends Service>, Service>();
		services.put(ServiceManager.class, this);
	}

	@SuppressWarnings("unchecked")
	public <S extends Service> S getService(Class<S> serviceClass) {

		Service service = services.get(serviceClass);
		if (service != null)
			return (S) service;

		synchronized (serviceClass) {
			service = services.get(serviceClass);
			if (service == null) {

				try {

					final Constructor<?> constructor = serviceClass
							.getDeclaredConstructor();
					constructor.setAccessible(true);
					service = (Service) constructor.newInstance();
					services.put(serviceClass, service);

				} catch (Exception e) {
					throw new IllegalStateException(message(serviceClass), e);
				}
			}
		}

		return (S) service;
	}

	public void clear() {

		services.clear();
		services.put(ServiceManager.class, this);
	}

	private <S> String message(Class<S> serviceClass) {
		return "[ServiceManager:" + serviceClass + "]";
	}
}
